<!DOCTYPE HTML>
<html lang="en-US" >
    
    <head>
        
        <meta charset="UTF-8">
        <title>逻辑分支 | Swift 入门</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 1.0.3">
        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
        
    
    
    
    <link rel="next" href="./03.html" />
    
    
    <link rel="prev" href="./01.html" />
    

        
    </head>
    <body>
        
        
<link rel="stylesheet" href="gitbook/style.css">


        
    <div class="book"  data-level="0.2" data-basepath="." data-revision="1441520019429">
    

<div class="book-summary">
    <div class="book-search">
        <input type="text" placeholder="Type to search" class="form-control" />
    </div>
    <ul class="summary">
        
    	
    	
    	

        

        
    
        
        <li class="chapter " data-level="0" data-path="index.html">
            
                
                    <a href="./index.html">
                        <i class="fa fa-check"></i>
                        
                         Swift 入门
                    </a>
                
            
            
            <ul class="articles">
                
    
        
        <li class="chapter " data-level="0.1" data-path="01.html">
            
                
                    <a href="./01.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.1.</b>
                        
                         常量&amp;变量
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter active" data-level="0.2" data-path="02.html">
            
                
                    <a href="./02.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.2.</b>
                        
                         逻辑分支
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.3" data-path="03.html">
            
                
                    <a href="./03.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.3.</b>
                        
                         循环
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.4" data-path="05.html">
            
                
                    <a href="./05.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.4.</b>
                        
                         数组
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.5" data-path="06.html">
            
                
                    <a href="./06.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.5.</b>
                        
                         字典
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.6" data-path="04.html">
            
                
                    <a href="./04.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.6.</b>
                        
                         字符串
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.7" data-path="07.html">
            
                
                    <a href="./07.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.7.</b>
                        
                         函数
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.8" data-path="08.html">
            
                
                    <a href="./08.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.8.</b>
                        
                         闭包
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.9" data-path="09.html">
            
                
                    <a href="./09.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.9.</b>
                        
                         懒加载
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.10" data-path="10.html">
            
                
                    <a href="./10.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.10.</b>
                        
                         getter &amp; setter
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="0.11" data-path="ats.html">
            
                
                    <a href="./ats.html">
                        <i class="fa fa-check"></i>
                        
                            <b>0.11.</b>
                        
                         ATS
                    </a>
                
            
            
        </li>
    

            </ul>
            
        </li>
    


        
        <li class="divider"></li>
        <li>
            <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Published using GitBook</a>
        </li>
        
    </ul>
</div>

    <div class="book-body">
        <div class="body-inner">
            <div class="book-header">
    <!-- Actions Left -->
    <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
    <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
    
    <div id="font-settings-wrapper" class="dropdown pull-left">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle font settings"><i class="fa fa-font"></i>
        </a>
        <div class="dropdown-menu font-settings">
    <div class="dropdown-caret">
        <span class="caret-outer"></span>
        <span class="caret-inner"></span>
    </div>

    <div class="buttons">
        <button type="button" id="reduce-font-size" class="button size-2">A</button>
        <button type="button" id="enlarge-font-size" class="button size-2">A</button>
    </div>

    <div class="buttons font-family-list">
        <button type="button" data-font="0" class="button">Serif</button>
        <button type="button" data-font="1" class="button">Sans</button>
    </div>

    <div class="buttons color-theme-list">
        <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button>
        <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button>
        <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button>
    </div>
</div>

    </div>

    <!-- Actions Right -->
    
    <div class="dropdown pull-right">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle share dropdown"><i class="fa fa-share-alt"></i>
        </a>
        <div class="dropdown-menu font-settings dropdown-left">
            <div class="dropdown-caret">
                <span class="caret-outer"></span>
                <span class="caret-inner"></span>
            </div>
            <div class="buttons">
                <button type="button" data-sharing="twitter" class="button">Twitter</button>
                <button type="button" data-sharing="google-plus" class="button">Google</button>
                <button type="button" data-sharing="facebook" class="button">Facebook</button>
                <button type="button" data-sharing="weibo" class="button">Weibo</button>
                <button type="button" data-sharing="instapaper" class="button">Instapaper</button>
            </div>
        </div>
    </div>
    

    
    <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
    
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="./" >Swift 入门</a>
    </h1>
</div>

            <div class="page-wrapper" tabindex="-1">
                <div class="page-inner">
                
                
                    <section class="normal" id="section-gitbook_9">
                    
                        <h1 id="">逻辑分支</h1>
<h2 id="">简单体验</h2>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> i = <span class="hljs-number">10</span>

<span class="hljs-keyword">if</span> i &gt; <span class="hljs-number">0</span> {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"OK"</span>)
}
</code></pre>
<ul>
<li>阶段性小结<ul>
<li><code>Swift</code> 中没有 C 语言中的<code>非零即真</code>概念</li>
<li>在逻辑判断时必须显示地指明具体的判断条件</li>
<li><code>if</code> 语句条件的 <code>()</code> 可以省略</li>
<li>但是 <code>{}</code> 不能省略</li>
</ul>
</li>
</ul>
<h2 id="">三目</h2>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>
<span class="hljs-keyword">var</span> b = <span class="hljs-number">50</span>

<span class="hljs-keyword">var</span> result = a &gt; b ? a : b
<span class="hljs-built_in">print</span>(result)
</code></pre>
<ul>
<li>阶段性小结<ul>
<li><code>Swift</code> 中的 <code>三目</code> 运算保持了和 OC 一致的风格</li>
</ul>
</li>
</ul>
<h2 id="">可选项</h2>
<h3 id="-1">演练 1</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> url = <span class="hljs-type">NSURL</span>(string: <span class="hljs-string">"http://www.520it.com/"</span>)

<span class="hljs-keyword">if</span> url != <span class="hljs-built_in">nil</span> {
    <span class="hljs-type">NSURLSession</span>.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, <span class="hljs-number">_</span>, <span class="hljs-number">_</span>) -&gt; <span class="hljs-type">Void</span> <span class="hljs-keyword">in</span>
        <span class="hljs-built_in">print</span>(<span class="hljs-type">NSString</span>(data: data!, encoding: <span class="hljs-type">NSUTF8StringEncoding</span>))
    }).resume()
}
</code></pre>
<ul>
<li><p>阶段性小结</p>
<ul>
<li><p>在 <code>Swift</code> 中，不是所有的对象实例化方法都会返回值，在实际开发中需要注意实例化函数的返回类型，例如：</p>
<pre><code class="lang-swift">convenience <span class="hljs-keyword">init</span>?(string <span class="hljs-type">URLString</span>: <span class="hljs-type">String</span>)
</code></pre>
</li>
<li><p>如果有 <code>?</code> 表示改方法有可能无法实例化到正确的对象</p>
</li>
<li>这种函数返回的对象，被称为 <code>可选项</code>，即有可能有值，也有可能没有值</li>
<li>实际开发时，需要针对这种对象加以判断，并且在分支内部使用 <code>!</code>，指明改对象确实是存在的</li>
<li>相比在 <code>OC</code> 的开发，尤其在日常练习时，会给定一个能够运行的值，而在实际运行时，一旦条件不满足，会直接闪退，这样用户体验会非常不好</li>
</ul>
</li>
</ul>
<blockquote>
<p><code>Swift</code> 的设计者考虑到因为对类型的强制要求，会让代码很难看，因此提供了一个变通的解决方案</p>
</blockquote>
<h3 id="-2">演练 2</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> url = <span class="hljs-type">NSURL</span>(string: <span class="hljs-string">"http://520it.com"</span>) {
    <span class="hljs-type">NSURLSession</span>.sharedSession().dataTaskWithURL(url, completionHandler: { (data, <span class="hljs-number">_</span>, <span class="hljs-number">_</span>) -&gt; <span class="hljs-type">Void</span> <span class="hljs-keyword">in</span>
        <span class="hljs-built_in">print</span>(<span class="hljs-type">NSString</span>(data: data!, encoding: <span class="hljs-type">NSUTF8StringEncoding</span>))
    }).resume()
}
</code></pre>
<ul>
<li><p>阶段性小结</p>
<ul>
<li>使用 <code>if let 常量 = 可选构造函数</code> 的方式能够确保分支内部常量一定是有值的</li>
<li>并且在分支内部不再需要使用 <code>!</code></li>
<li>这是 <code>Swift</code> 代码中的一个非常重要的使用技巧</li>
</ul>
</li>
<li><p>提示</p>
<ul>
<li>尽管 <code>Swift</code> 提供了类型校验的手段，但是要写出 <code>优雅</code> 的 Swift 代码，还是需要多加练习的，否则一不小心就会出现分支嵌套层次很深的代码</li>
<li>有关 <code>?</code> 和 <code>!</code> 的选择，可以借助 Xcode 的辅助工具，但是强烈建议每次遇到提示时，要多加思考，反复揣摩</li>
</ul>
</li>
</ul>
<h3 id="3">演练3</h3>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>?
<span class="hljs-built_in">print</span>(name?.lengthOfBytesUsingEncoding(<span class="hljs-type">NSUTF8StringEncoding</span>))

name = <span class="hljs-string">"lnj"</span>
<span class="hljs-built_in">print</span>(name?.lengthOfBytesUsingEncoding(<span class="hljs-type">NSUTF8StringEncoding</span>))

<span class="hljs-keyword">let</span> l = <span class="hljs-number">10</span>
<span class="hljs-built_in">print</span>(l + (name?.lengthOfBytesUsingEncoding(<span class="hljs-type">NSUTF8StringEncoding</span>) ?? <span class="hljs-number">0</span>))
</code></pre>
<ul>
<li>阶段性小结<ul>
<li><code>??</code> 是一个非常有用的操作符，能够快速对 <code>nil</code> 进行判断</li>
<li>如果对象是 <code>nil</code>，则使用 <code>??</code> 后面的值代替前面的 <code>nil</code> 值参与计算</li>
<li>在使用 <code>??</code> 时，整个部分需要使用 <code>()</code> 包装</li>
<li>这一技巧在 <code>UITableView</code> 的数据源方法中尤为重要</li>
</ul>
</li>
</ul>

                    
                    </section>
                
                
                </div>
            </div>
        </div>

        
        <a href="./01.html" class="navigation navigation-prev " aria-label="Previous page: 常量&amp;变量"><i class="fa fa-angle-left"></i></a>
        
        
        <a href="./03.html" class="navigation navigation-next " aria-label="Next page: 循环"><i class="fa fa-angle-right"></i></a>
        
    </div>
</div>

        
<script src="gitbook/app.js"></script>

    
    <script src="https://cdn.mathjax.org/mathjax/2.4-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    
    <script src="gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
    

<script>
require(["gitbook"], function(gitbook) {
    var config = {"fontSettings":{"theme":null,"family":"sans","size":2}};
    gitbook.start(config);
});
</script>

        
    </body>
    
</html>
